<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      :row-class-name="tableRowClassName"
      :cell-style="cellStyle"
      @cell-dblclick="handleRowClick"
    >
      <template slot="icon" slot-scope="scope">
        <i :class="scope.row.icon" style="font-size: 24px"></i>
      </template>
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-view" size="small" @click.stop="viewSequenceNumber(row)">查看序列号</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!--        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>-->
      <!-- <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button> -->
      <template slot="menuLeft">
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出 </el-button>
      </template>
    </avue-crud>
    <el-dialog title="查看" :visible.sync="showDetailDialog" width="60%" append-to-body="true">
      <avue-crud
        ref="detailCrud"
        :option="detailOption"
        :table-loading="detailLoading"
        :page.sync="detailPage"
        :data="detailData"
        @current-change="detailCurrentChange"
        @size-change="detailSizeChange"
        @refresh-change="detailRefreshChange"
      >
        <template slot="menuLeft">
          <el-button type="warning" size="small" icon="el-icon-download" @click="detailExport">导出</el-button>
        </template></avue-crud
      >
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <!-- <export-excel
      :visible="exprotVisible"
      :loading="loading"
      :option="option"
      :page="page"
      :data="exportData"
      name="成品包装"
      @selectData="handleSelectData"
      @close="handleClose"
    ></export-excel> -->
    <export-comp ref="exportComp" page-api-url="" :option="option" :page="page" reportCode="productPack_export" :query="query" file-name="成品包装"> </export-comp>
    <export-comp
      ref="detailExportComp"
      page-api-url="mes-product/statistics/find-product-by-pack-id-page"
      :option="detailOption"
      :page="detailPage"
      reportCode="productPackDetail_export"
      :query="detailQuery"
      file-name="成品包装详情"
    ></export-comp>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getPackStatusList, getDetailList, exportListData } from '@/api/report/finished-product-package-query';
import exportExcel from '@/components/export-excel';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { productExport } from '@/api/admin/barcode-record';
import { filterEmptyValues } from '@/util/util';

export default {
  name: 'ReportFinishedProductPackageQuery',
  components: {
    CommonModalTemplate,
    exportExcel,
    userTableConfig,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'FINISH_PRODUCT_PACKAGE_QUERY',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      exprotVisible: false,
      exportData: [],
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      query: {},
      loading: false,
      search: {},
      selectionList: [],
      option: {
        height: 'calc(100vh - 480px)',
        calcHeight: 30,
        tree: true,
        expandRowKeys: [],
        // rowKey: 'packNo',
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        searchLabelWidth: 100,
        border: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        index: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        menu: true,
        columnBtn: false,
        column: [
          {
            label: '序号',
            prop: 'index'
          },
          {
            label: '包装条码',
            prop: 'packNo',
            search: true
          },
          {
            label: '包装类型',
            prop: 'packType',
            type: 'select',
            dicData: [
              {
                label: '外包装',
                value: 'ProductOutPack'
              },
              {
                label: '内包装',
                value: 'ProductInnerPack'
              }
            ]
          },
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            search: true,
            hide: true
          },
          {
            label: '包装数量',
            prop: 'packQuantity'
          },
          {
            label: '重量',
            prop: 'packWeight'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产品型号',
            prop: 'partName'
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true
          },
          {
            label: '包装时间',
            prop: 'packingPackedDate'
          },
          // {
          //   label: '标签打印时间',
          //   prop: 'packingCreateTime'
          // },
          {
            label: '包装状态',
            prop: 'packStatus',
            type: 'select',
            dicData: [
              {
                label: '正常',
                value: 1
              },
              {
                label: '全部锁定',
                value: 2
              },
              {
                label: '部分锁定',
                value: 3
              },
              {
                label: '报废',
                value: 4
              },
              {
                label: '已出库',
                value: 5
              },
              {
                label: '已入库',
                value: 6
              }
            ]
          }
        ]
      },
      data: [],
      allData: [],
      selectIndex: '',
      detailOption: {
        height: '500px',
        calcHeight: 30,
        tip: false,
        border: true,
        selection: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        menu: false,
        columnBtn: false,
        column: [
          {
            label: '序列号',
            prop: 'sequenceNumber'
          },
          {
            label: '载具数量',
            prop: 'packingSpecification'
          },
          {
            label: '子件序列号',
            prop: 'componentSns',
            overHidden: true,
            formatter: (row, val) => {
              if (val && val != null) {
                return val
                  .split(',')
                  .filter((i) => i)
                  .join('、');
              }
            }
          }
        ]
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailQuery: {},
      showDetailDialog: false,
      detailLoading: false,
      detailData: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    const packStatus = this.findObject(this.option.column, 'packStatus');
    getPackStatusList().then(
      (res) => {
        let packStatusList = [];
        packStatusList = this._get(res, 'data.data', []);
        packStatus.dicData = this._map(packStatusList, (item) => {
          return {
            label: item.dictValue,
            value: Number(item.dictKey)
          };
        });
      },
      (error) => {
        packStatus.dicData = [];
      }
    );
  },
  methods: {
    searchReset() {
      this.query = {};
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      const page = {
        current,
        pageSize
      };
      this.onLoad(page);
    },
    // handleExport() {
    //   let data = [];
    //   this.data.forEach((item) => {
    //     let children = [];
    //     item.level = '外包装';
    //     if (item.children && item.children.length > 0) {
    //       children = item.children;
    //     }
    //     this._forEach(children, (c) => {
    //       c.level = '内包装';
    //     });
    //     data.push(item, ...children);
    //   });
    //   console.log(data, '8899');
    //   this.exportData = this._cloneDeep(data);
    //   this.exprotVisible = true;
    // },
    // handleClose(val) {
    //   this.exprotVisible = false;
    //   this.data = this.exportData.splice(0, this.page.pageSize);
    // },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.data = this.allData.slice(Number(currentPage - 1) * Number(this.page.pageSize), Number(currentPage) * Number(this.page.pageSize));
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].children) {
          this.forFunction(this.data[i].children, this.data[i].index);
        }
      }
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.currentPage = 1;
      this.data = this.allData.slice(0, this.page.pageSize);
      for (let i = 0; i < this.data.length; i++) {
        if (this.data[i].children) {
          this.forFunction(this.data[i].children, this.data[i].index);
        }
      }
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    validateObject(obj) {
      let count = 0;
      if (obj.packNo) {
        count++;
      }
      if (obj.productSequenceNumber) {
        count++;
      }
      if (obj.workOrderNo) {
        count++;
      }
      return count !== 1;
    },
    onLoad(page, params = {}) {
      console.log(Object.keys(this.query));
      // if (!this.loading) {
      // if (this.validateObject(this.query)) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请输入包装条码、序列号、工单号三个查询条件中的其中一项进行查询！'
      //   });
      //   return;
      // }
      if (Object.keys(this.query).length == 0) {
        this.$message.warning('请至少输入一个查询条件!');
        return;
      }
      this.loading = true;
      this.option.expandRowKeys = [];
      this.selectIndex = '';
      getList(Object.assign(params, this.query)).then((res) => {
        this.allData = res.data.data && res.data.data != null ? res.data.data : [];
        this.page.total = this.allData.length;
        this.allData.forEach((item, index) => {
          item.isRoot = true;
          item.index = index + 1;
        });
        this.data = this.allData.slice(0, 15);
        this.loading = false;
        this.exportData = this.data;
        this.loading = false;
        for (let i = 0; i < this.data.length; i++) {
          this.data[i]['index'] = i + 1;
          if (this.query.packNo && this.query.productSequenceNumber) {
            if (this.data[i].packNo === this.query.packNo) {
              this.selectIndex = i;
              break;
            }
            if (this.data[i].packNo != this.query.packNo && this.data[i].children) {
              this.option.expandRowKeys.push(this.data[i].packNo);
              this.forFunction(this.data[i].children, this.data[i].index);
            }
          } else if (this.query.packNo) {
            if (this.data[i].packNo === this.query.packNo) {
              this.selectIndex = i;
              break;
            }
            if (this.data[i].packNo != this.query.packNo && this.data[i].children) {
              this.option.expandRowKeys.push(this.data[i].packNo);
              this.forFunction(this.data[i].children, this.data[i].index);
            }
          } else if (this.query.productSequenceNumber) {
            if (this.data[i].isContain && this.data[i].isContain != null) {
              this.selectIndex = i;
              break;
            }
            if (!this.data[i].isContain && this.data[i].children) {
              this.option.expandRowKeys.push(this.data[i].packNo);
              this.forFunction(this.data[i].children, this.data[i].index);
            }
          } else {
            if (this.data[i].children) {
              this.forFunction(this.data[i].children, this.data[i].index);
            }
          }
        }
      });
      // getList(this.query).then((res) => {
      //   this.data = res.data.data.map((item, index) => {
      //     item.dataIndex = index + 1;
      //     return item;
      //   });

      // });
      // } else {
      //   this.loading = false;
      // }
    },
    forFunction(list, index) {
      for (let j = 0; j < list.length; j++) {
        list[j]['index'] = index + '-' + (j + 1);
        if (this.query.packNo) {
          if (list[j].packNo === this.query.packNo) {
            this.selectIndex = j + this.option.expandRowKeys.length;
            break;
          }
          if (list[j].packNo != this.query.packNo && list[j].children) {
            this.option.expandRowKeys.push(list[j].packNo);
            this.forFunction(list[j].children, list[j].index);
          }
        } else if (this.query.productSequenceNumber) {
          if (list[j].isContain && list[j].isContain != null) {
            this.selectIndex = j + this.option.expandRowKeys.length;
            break;
          }
          if (!list[j].isContain && list[j].children) {
            this.option.expandRowKeys.push(list[j].packNo);
            this.forFunction(list[j].children, list[j].index);
          }
        } else {
          if (list[j].children) {
            this.forFunction(list[j].children, list[j].index);
          }
        }
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === this.selectIndex) {
        return 'scan-entry-row';
      }
      return '';
    },
    openWorkOrderNoCommonModal() {
      this.modalName = 'workOrderNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderNoModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          break;
        default:
          break;
      }
      if (rowData.sequenceNumber) {
        this.$router.push({
          path: '/report/forward-trace-back-to',
          query: { sequenceNumber: rowData.sequenceNumber }
        });
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 7) {
        return {
          color: '#409eff',
          cursor: 'pointer'
        };
      }
    },
    //表格双击
    handleRowClick(row, column, cell, event) {
      if (column.label == '工单号' && row.workOrderNo) {
        this.$router.push({
          path: '/product/workOrderProgress',
          query: { workOrderNo: row.workOrderNo }
        });
      }
    },
    /**
     * 查看产品序列号
     */
    viewSequenceNumber(row) {
      this.detailQuery['packId'] = row.packId;
      this.showDetailDialog = true;
      this.detailLoading = true;
      this.queryDetailList(this.detailPage, { packId: row.packId });
    },
    queryDetailList(page, params = {}) {
      getDetailList(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {
        const data = res.data.data;
        this.detailPage.total = data.total;
        this.detailData = data.records;
        this.detailLoading = false;
      });
    },
    // detailExport() {
    //   this.$refs.detailExportComp.visible = true;
    // },
    detailCurrentChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.queryDetailList(this.detailPage, this.detailQuery);
    },
    detailSizeChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.queryDetailList(this.detailPage, this.detailQuery);
    },
    detailRefreshChange() {
      this.queryDetailList(this.detailPage, this.detailQuery);
    },
    async handleExport() {
      const column = this.option.column.filter((i) => !i.hide);
      const colunmJson = {};
      column.forEach((item) => {
        colunmJson[item.label] = item.prop;
      });
      // 后端的顶级设计 无法理解 故写死
      colunmJson['产品型号'] = 'partModel';
      colunmJson['包装状态'] = 'packingStatus';
      colunmJson['包装时间'] = 'packedDate';
      // if (this.validateObject(this.search)) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请输入包装条码、序列号、工单号三个查询条件中的其中一项进行导出！'
      //   });
      //   return;
      // }
      if (this.data.length === 0) {
        this.$message.warning('列表中不存在数据，请查询出数据后再导出！');
        return;
      }
      const params = this._cloneDeep(this.search);
      params.columnHeaders = JSON.stringify(colunmJson);
      const loading = this.$loading({
        lock: true,
        text: '数据导出中请稍等。',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const res = await exportListData(filterEmptyValues(params));
        const blob = new Blob([res.data]);
        const fileName = '成品包装导出.xlsx';
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        const failMsg = await this.blobToJson(e.data);
        this.$message.error(failMsg.msg);
      } finally {
        loading.close();
      }
    },
    async blobToJson(blob) {
      return new Promise((resolve, reject) => {
        blob.arrayBuffer().then(
          async (arrayBuffer) => {
            resolve(JSON.parse(Buffer.from(arrayBuffer).toString('utf-8')));
          },
          (error) => {
            reject(error);
          }
        );
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table .scan-entry-row {
  background: #caf982;
}
</style>
